
#################### 1、序列化器，序列化单个书籍对象 ####################
from apps.drf_test_2定义序列化器.serializers import BookInfSerizlizer
from apps.drf_test_0Django原始restful.models import BookinfoModels

# 获取单个书籍对象
book = BookinfoModels.objects.get(id = 1)
# 创建序列化器，instance，表示要序列化的对象
serizlizer = BookInfSerizlizer(instance=book)
# 转换书籍
print(serizlizer.data)
"""
结果：
    {'id': 1, 'btitle': '童话故事', 'bpub_date': '1985-04-12', 'bread': 20, 'bcomment': 10, 'is_delete': False}
"""


#################### 2、序列化器，序列化列表书籍对象 ####################
from apps.drf_test_2定义序列化器.serializers import BookInfSerizlizer
from apps.drf_test_0Django原始restful.models import BookinfoModels

# 获取多个书籍对象
books = BookinfoModels.objects.all()
# 创建序列化器
serizlizer = BookInfSerizlizer(instance=books,many=True)
print(serizlizer.data)
"""
结果：
    [
    OrderedDict([('id', 1), ('btitle', '童话故事'), ('bpub_date', '1985-04-12'), ('bread', 20), ('bcomment', 10), ('is_delete', False)]), 
    OrderedDict([('id', 2), ('btitle', '青春期的哪些事'), ('bpub_date', '1995-04-12'), ('bread', 10), ('bcomment', 5), ('is_delete', False)]), 
    OrderedDict([('id', 6), ('btitle', '一步到位学python'), ('bpub_date', '2005-06-08'), ('bread', 10), ('bcomment', 50), ('is_delete', False)]), 
    OrderedDict([('id', 7), ('btitle', '一步到位学python'), ('bpub_date', '2005-06-08'), ('bread', 10), ('bcomment', 50), ('is_delete', False)])
    ]
"""
#################### 3、序列化器，测试反序列化 ####################
from apps.drf_test_2定义序列化器.serializers import BookInfSerizlizer
from apps.drf_test_0Django原始restful.models import BookinfoModels

book_dict = {
    "btitle": "数学就该这样学",
    "bpub_date": "2019-06-08",
    "bread": 1000,
    "bcomment": 111
}

serizlizer = BookInfSerizlizer(data=book_dict)
serizlizer.is_valid(raise_exception=True)
serizlizer.save()
print(serizlizer.data)

#################### 3、序列化器，测试反序列化,更新入库 ####################
from apps.drf_test_2定义序列化器.serializers import BookInfSerizlizer
from apps.drf_test_0Django原始restful.models import BookinfoModels

book_dict = {
    "btitle": "数学就该这样学",
    "bpub_date": "2019-06-08",
    "bread": 1000,
    "bcomment": 111
}
book = BookinfoModels.objects.get(id = 12)

serizlizer = BookInfSerizlizer(instance=book,data=book_dict)
serizlizer.is_valid(raise_exception=True)
serizlizer.save()
print(serizlizer.data)



#################### 2、序列化器，序列化单个英雄对象 ####################
from apps.drf_test_2定义序列化器.serializers import HeroSerizlizer
from apps.drf_test_0Django原始restful.models import HeroinfoModels
hero = HeroinfoModels.objects.get(id = 1)
ser = HeroSerizlizer(instance=hero)
print(ser.data)
"""
结果：
    {'id': 1, 'hname': '黄蓉', 'hgender': 0, 'hcomment': '特色看了几个'}
"""
